import Immutable from 'immutable'
import * as Utils from '../utils'

function initRestState() {
	return Immutable.fromJS({
		isSuccess: false,
		isFailed: false,
		response: {},
	})
}

const GET_USER_PROFILE = initRestState()
const CREATE_USER = initRestState()
const IS_USER_EXIST = initRestState()

const restCallStateHolder = Immutable.fromJS({
	GET_USER_PROFILE,
	CREATE_USER,
	IS_USER_EXIST,
})

export default function restReducer(states = restCallStateHolder, action) {
	let operation = {
		REST_START: () => states.update(action.restCallName, (restCallState) => restCallState.merge({
			isSuccess: false,
			isFailed: false,
			response: {}
		})),
		REST_CLEAR: () => states.update(action.restCallName, (restCallState) => restCallState.merge({
			isSuccess: false,
			isFailed: false,
			response: {}
		})),
		REST_SUCCESS: () => states.update(action.restCallName, (restCallState) => restCallState.merge({
			isSuccess: true,
			isFailed: false,
			response: action.skipToJson ? action.response : Object.assign({}, action.response)
		})),
		REST_FAILED: () => states.update(action.restCallName, (restCallState) => restCallState.merge({
			isSuccess: false,
			isFailed: true,
			response: Object.assign({}, action.response)
		}))
	}
	if (operation[action.callStage]) {
		return operation[action.callStage]()
	}

	return states
}